package com.xyzwps.ewa.modules.auth

import com.xyzwps.ewa.common.CookieNames
import com.xyzwps.ewa.modules.auth.payload.UsernamePasswordLoginPayload
import com.xyzwps.ewa.modules.auth.session.Session
import com.xyzwps.ewa.modules.auth.session.SessionIdGenerator
import com.xyzwps.ewa.modules.auth.session.Sessions
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import java.time.LocalDateTime

const val SESSION_EXPIRES_IN_DAYS = 7

fun Route.authRoutes() {

    route("/login/up") {
        post {
            val payload = call.receive<UsernamePasswordLoginPayload>()
            // TODO: 多次登录失败，则关闭账户
            val user = UsernamePasswordLoginService.login(payload.username, payload.password)
            val session = Session(
                userId = user.id,
                sessionId = SessionIdGenerator.generate(),
                start = LocalDateTime.now(),
                end = LocalDateTime.now().plusDays(SESSION_EXPIRES_IN_DAYS.toLong())
            )
            Sessions.save(session)
            call.response.cookies.append(
                Cookie(
                    name = CookieNames.SID,
                    value = session.sessionId,
                    maxAge = SESSION_EXPIRES_IN_DAYS * 24 * 3600,
                    path = "/",
                    httpOnly = true
                )
            )
            call.respond(HttpStatusCode.OK, user)
        }
    }

    post("/logout") {
        call.response.cookies.append(
            Cookie(
                name = CookieNames.SID,
                value = "",
                maxAge = 0,
                path = "/",
                httpOnly = true
            )
        )
        call.respond(HttpStatusCode.OK)
    }

}